<template>
  <div style="background: #F0F3F4">
    <!--页面头部-->
    <div class="bg-light lter b-b wrapper-md manage-school-title-box">
      <h1 class="m-n text-black font-thin">{{ $t('loc.mgStf') }}</h1>
      <div class="input-group">
        <el-input v-if="false" size="small" v-model="searchContent" class="manage-school-search"
                  :placeholder="$t('loc.1stNameReq')" :suffix-icon="Search"></el-input>
      </div>
    </div>
    <!--页面内容-->
    <div>
      <div class="flex-space-between lg-pa-10">
        <div>
          <el-select v-model="selectedSchoolId" class="add-margin-lr-10" :placeholder="$t('loc.selectCenter')" size="large">
            <el-option
                v-for="item in schoolOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
          <el-button type="danger" @click="bthDeletedStaffClickHandler">{{ $t('loc.bthSel') }}</el-button>
        </div>
        <div>
          <el-button type="primary" @click="addStaffClickHandler">{{ $t('loc.addStf') }}</el-button>
        </div>
      </div>

      <div>
        <el-table
            ref="StaffsTableRef"
            :data="staffs"
            style="width: 96%"
            stripe
            border
        >
          <el-table-column type="selection" width="55"/>
          <el-table-column :label="$t('loc.stfName')">
            <template #default="scope">
              <div>
                {{ scope.row.userName }}
                <el-icon @click="editStaffHandler(scope.row)" class="pointer">
                  <svg-icon type="mdi" :path="mdiPencil"></svg-icon>
                </el-icon>
              </div>
              <div>
                {{ scope.row.email }}
              </div>
                </template>
          </el-table-column>
          <el-table-column :label="$t('loc.site')" width="200" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.role === 'AGENCY_OWNER' || scope.row.role === 'AGENCY_ADMIN'">
                  {{ $t('loc.allCenter') }}
              </span>
              <span v-else class="font-color-gray">
                  {{ (scope.row.schools.map(school => school.name).join(',')) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column property="address" :label="$t('loc.role')" width="200" show-overflow-tooltip>
            <template #default="scope">
              <div>
                {{ formatRole(scope.row.role) }}
              </div>
              <span class="font-color-gray">
                 {{ scope.row.role === 'TEACHER' ? scope.row.schools.flatMap(school => school.groups).map(group => group.name).join(',') : '' }}
              </span>
            </template>
          </el-table-column>

          <el-table-column property="address" :label="$t('loc.manAddRoster')">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.userMetaMap['MANUAL_ADDING_ROSTER_OPEN_FLAG']"
                  size="large"
                  inline-prompt
                  active-text="Open"
                  inactive-text="Close"
                  :before-change="switchBeforeChange.bind(this, 'MANUAL_ADDING_ROSTER_OPEN_FLAG', scope.row)"
                  :disabled="scope.row.role === 'AGENCY_OWNER' || scope.row.role === 'AGENCY_ADMIN'"
              />
            </template>
          </el-table-column>
          <el-table-column v-if="false" sproperty="address" :label="$t('loc.noteReview')">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.userMetaMap['APPROVAL_OPEN_FLAG']"
                  size="large"
                  inline-prompt
                  active-text="Open"
                  inactive-text="Close"
                  :before-change="switchBeforeChange.bind(this, 'APPROVAL_OPEN_FLAG', scope.row)"
                  :disabled="scope.row.role === 'AGENCY_OWNER' || scope.row.role === 'AGENCY_ADMIN'"
              />
            </template>
          </el-table-column>
          <el-table-column sproperty="address" :label="'评分权限'">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.userMetaMap['RATING_OPEN_FLAG']"
                  size="large"
                  inline-prompt
                  active-text="Open"
                  inactive-text="Close"
                  :before-change="switchBeforeChange.bind(this, 'RATING_OPEN_FLAG', scope.row)"
                  :disabled="scope.row.role === 'AGENCY_OWNER' || scope.row.role === 'AGENCY_ADMIN' || scope.row.role === 'SCHOOL_ADMIN'"
              />
            </template>
          </el-table-column>
          <el-table-column property="address" label="通知权限">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.userMetaMap['SCHOOL_MESSAGE_FLAG']"
                  size="large"
                  inline-prompt
                  active-text="Open"
                  inactive-text="Close"
                  :before-change="switchBeforeChange.bind(this, 'SCHOOL_MESSAGE_FLAG', scope.row)"
                  :disabled="scope.row.role === 'AGENCY_OWNER' || scope.row.role === 'AGENCY_ADMIN'"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <AddStaffDialog
        :staff="operatedStaff"
        v-model:dialogVisible="addStaffDialogVisible"
        @needReLoadData="initData">
    </AddStaffDialog>
  </div>
</template>

<script>
import SvgIcon from '@jamescoyle/vue-icon';
import { mdiPencil } from '@mdi/js';
import {Search, CaretBottom, CaretRight, Edit} from "@element-plus/icons-vue";
import SchoolApi from "@/api/school";
import UserApi from "@/api/user";
import {useStore} from "vuex";
import AddStaffDialog from "@/views/admin/manageStaffs/AddStaffDialog";
import tools from "@/utils/tools";

export default {
  name: "manageStaffs",
  components: {
    AddStaffDialog,
    Search,
    CaretBottom,
    CaretRight,
    Edit,
    SvgIcon
  },
  data() {
    return {
      mdiPencil: mdiPencil,
      agency: {},
      staffs: [],
      dialogSchoolVisible: false,
      selectedSchoolId: '',
      schools: [],
      searchContent: '',
      Search: Search,
      addStaffDialogVisible: false,
      operatedStaff: {},
    }
  },
  watch: {
    selectedSchoolId: function (newVal, oldVal) {
      let groupIds = this.selectedGroupIdsOptions
      let schoolIds = [newVal]
      if (newVal === 'all school') {
        schoolIds = this.schools.map(school => school.id)
      }
      this.loadStaffs(this.currentAgencyId, schoolIds, groupIds)
    }
  },
  created() {
    this.initData()
  },
  computed: {
    currentUser() {
      return useStore().state.user.currentUser
    },
    currentAgencyId() {
      return this.currentUser.currentAgencyId
    },
    schoolOptions() {
      let schools = this.schools
      schools.unshift({id: 'all school', name: this.$t('loc.allCenter')})
      return schools
    },
    selectedGroupIdsOptions() {
      let selectedSchool = this.schools.find(school => school.id === this.selectedSchoolId) || {}
      if (selectedSchool.id === 'all school' || !selectedSchool.groups) {
        return []
      }
      return selectedSchool.groups.map(group => group.id) || []
    },
  },
  methods: {
    initData() {
      let userId = this.currentUser.userId
      let currentAgencyId = this.currentAgencyId || useStore().state.user.currentUser.currentAgencyId
      this.isSchoolsLoading = true
      SchoolApi.getSchoolsGroupByUserId(userId).then(res => {
        this.schools = res
        // schools 中的 Id 拿出來 schoolIds
        let schoolIds = []
        let groupIds = []
        // 如果当前用户有选择幼儿园，那么就只加载当前幼儿园的数据
        if (this.selectedSchoolId && this.schools.find(school => school.id === this.selectedSchoolId)) {
          groupIds = this.selectedGroupIdsOptions
          schoolIds = [newVal]
          if (newVal === 'all school') {
            schoolIds = this.schools.map(school => school.id)
          }
        } else  {
          schoolIds = this.schools.map(school => school.id)
          groupIds = this.schools.flatMap(school => school.groups).map(group => group.id)
        }
        this.loadStaffs(currentAgencyId, schoolIds, groupIds)
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.isSchoolsLoading = false
      })
    },
    loadStaffs(agencyId, schoolIds, groupIds) {
      if (!agencyId && !schoolIds && !groupIds && schoolIds.length === 0 && groupIds.length === 0) {
        return
      }
      UserApi.getStaffs(agencyId, schoolIds.toString(), groupIds.toString()).then(res => {
        res.staffs.forEach(staff => {
          let userMetaMap = staff.userMetaMap
          // userMetaMap 循环 将 value 转换为 boolean
          for (let key in userMetaMap) {
            userMetaMap[key] = (userMetaMap[key] === 'true' || userMetaMap[key] === '1') ? true : false
          }
        })
        this.staffs = res.staffs
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.isSchoolsLoading = false
      })
    },
    bthDeletedStaffClickHandler (staff) {
      this.$confirm(this.$t('loc.wantRmvStaff'), this.$t('loc.tip'), {
        confirmButtonText: this.$t('loc.confirm'),
        cancelButtonText: this.$t('loc.cancel'),
        type: 'warning'
      }).then(() => {
        let selectionRows = this.$refs.StaffsTableRef.getSelectionRows()
        let staffIds = selectionRows.map(item => item.id)
        UserApi.batchDeleteStaff({staffIds}).then(res => {
          this.$message.success(this.$t('loc.staffDeleted'))
          this.initData()
        }).catch(error => {
          this.$message.error(error.response.data.description)
        })
      }).catch(() => {
      })
    },
    addStaffClickHandler() {
      this.addStaffDialogVisible = true
      this.operatedStaff = {}
    },
    editStaffHandler(staff) {
      this.addStaffDialogVisible = true
      this.operatedStaff = staff
    },
    dialogSchoolClosed() {
    },
    operateGroupHandler(type, data) {
    },
    // 格式化角色显示
    formatRole (role) {
      return tools.formatRole(role)
    },
    switchBeforeChange(key, staff) {
      return new Promise((resolve) => {
        let userMetaMap = staff.userMetaMap
        let value = userMetaMap[key]
        let newValue = !value
        let open = {
          userId: staff.id,
          open: newValue,
        }
        let opens = {opens: [open]}
        console.log('switchBeforeChange', opens,key)
        if (key === 'APPROVAL_OPEN_FLAG') {
          UserApi.setApprovalSwitch(opens).then(res => {
            return resolve(true)
          }).catch(error => {
            return resolve(false)
          }).finally(() => {
          })
        } else if (key === 'MANUAL_ADDING_ROSTER_OPEN_FLAG') {
          UserApi.setRosterSwitch(opens).then(res => {
            return resolve(true)
          }).catch(error => {
            return resolve(false)
          }).finally(() => {
          })
        } else if (key === 'SCHOOL_MESSAGE_FLAG') {
          UserApi.setNotificationSwitch(opens).then(res => {
            return resolve(true)
          }).catch(error => {
            return resolve(false)
          }).finally(() => {
          })
        } else if (key === 'RATING_OPEN_FLAG'){
          UserApi.setRatingSwitch(opens).then(res => {
            return resolve(true)
          }).catch(error => {
            return resolve(false)
          }).finally(() => {
          })
        }
      })

    },

  },
  mounted() {
  }
}
</script>

<style scoped lang="less">
.manage-school-title-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.manage-school-search {
  width: 240px;
  height: 34px;

  /deep/ .el-input__wrapper {
    border-radius: 20px;
  }
}

.manage-school-main {
  display: block;
  padding: 30px 50px 0 30px;
  margin: 0 auto;
  height: 100%;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
  background-color: #0a1015;
}

/deep/ .el-collapse-item__wrap {
}

/deep/ .el-collapse {
  border-width: 0;
}

/deep/ .el-collapse-item__header {
}

.school-data-tables {
  display: flex;
  flex-wrap: wrap;
  gap: 50px;
  overflow-y: auto;
  // flex 元素间隔
  .school-data-table-div {
    height: fit-content;
    padding: 10px 20px;
    width: calc((100% - 180px) / 2);
    background-color: #fff;
    border: 1px solid transparent;
    border-radius: 4px;
    -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
    box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
  }
}

.group-name {
  font-size: 14px;
  font-weight: 700;
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}
</style>
